package com.one.filter;

import com.one.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
//@WebFilter(urlPatterns = "/*", filterName = "jwtTokenFilter")   //注释即可使失效，或者启动类注释注解@EnableWebMvc
public class JwtTokenFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("JwtTokenFilter 初始化");
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        log.info("JwtTokenFilter 执行过滤");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取请求路径
        String requestURI = request.getRequestURI();

        // 放行登录、注册、swagger相关请求
        if(requestURI.contains("/login")
                || requestURI.contains("/register")
                || requestURI.contains("/doc.html")
                || requestURI.contains("/swagger")
                || requestURI.contains("/v2/api-docs")
                || requestURI.contains("/swagger-resources")
                || requestURI.contains("/webjars/")) {
            log.info("请求放行: {}", requestURI);
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        //否则，获取Token校验确定是否放行
        String token=request.getHeader("token");
        if(token == null || token.isEmpty() ) { //令牌为空，返回401
            log.warn("请求 {} 缺少Token，拒绝访问", requestURI);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        //校验jwt令牌，如果令牌解析过程异常，说明令牌非法，返回401
        try{
            JwtUtil.parseJWT("oneoneone",token);
        }catch (Exception e){
            log.info("令牌非法");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        //令牌合法，放行
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
